<?php

namespace app\api\controller;

use app\admin\model\ConfigValueModel;
use app\admin\model\FeedbackModel;
use app\common\controller\Api;


class Feedback extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @var FeedbackModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new FeedbackModel();
    }

    public function index()
    {
        $status = $this->request->param('status/d',0);
        $list = $this->model
            ->where('user_id', $this->auth->id)
            ->where('status', $status)
            ->field('id,type,create_time,content,mobile,images')
            ->order('id', 'desc')
            ->paginate(15)->each(function ($item) {
                $item->append(['type_text']);
            });

        $this->success('请求成功', $list);
    }

    public function detail()
    {
        $id = $this->request->get('id/d', 0);
        $row = $this->model
            ->where('user_id', $this->auth->id)
            ->find($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $row->append(['reply_time_text', 'status_text']);
        $this->success('success', $row);
    }

    public function option_list()
    {
        $data = (new ConfigValueModel())->getOptionList(ConfigValueModel::TYPE_FEEDBACK);
        $this->success('success', $data);
    }

    public function add()
    {
        $params = $this->request->post();
        if (empty($params['type'])) {
            $this->error('类型不能为空');
        }
        if (empty($params['content'])) {
            $this->error('内容不能为空');
        }
        $option_list = (new ConfigValueModel())->getOptionList(ConfigValueModel::TYPE_FEEDBACK);
        if (!array_key_exists($params['type'], $option_list)) {
            $this->error('类型错误');
        }

        $create = $this->model->create([
            'user_id' => $this->auth->id,
            'type' => $params['type'],
            'content' => $params['content'],
            'images' => empty($params['images']) ? null : json_encode($params['images']),
            'mobile' => $params['mobile'] ?? '',
        ]);

        if ($create->id) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }
}
